package com.bscc.admin.dict;


import com.bscc.common.model.Dict;
import com.jfinal.plugin.activerecord.Db;

import java.util.ArrayList;
import java.util.List;

public class DictService
{
    private static final Dict dao = new Dict().dao();

    public List<Dict> findTypeList()
    {
        return dao.find("SELECT * FROM bw_dict WHERE type=1 ORDER BY sort");
    }

    public List<Dict> findTreeList()
    {
        List<Dict> dictList = dao.find("SELECT * FROM bw_dict ORDER BY sort");
        List<Dict> resultList = new ArrayList<Dict>();

        if(null != dictList && dictList.size() > 0)
        {
            for(Dict dr:dictList)
            {
                if(1 == dr.getType())
                {
                    resultList.add(dr);
                    for(Dict dc:dictList)
                    {
                        if(dr.getId() == dc.getPid())
                        {
                            resultList.add(dc);
                        }
                    }
                }
            }
        }
        return resultList;
    }


    public List<Dict> findDictByMark(String mark)
    {
        return dao.find("SELECT * FROM bw_dict WHERE pid=(SELECT id FROM bw_dict WHERE mark=?) ORDER BY sort", mark);
    }

    public Dict findById(int id)
    {
        Dict dict = dao.findById(id);
        if(null != dict && null != dict.getPid() && dict.getType() == 2)
        {
            Dict pDict = dao.findById(dict.getPid());
            if(null != pDict)
            {
                dict.setPname(pDict.getName());
            }

        }
        return dao.findById(id);
    }

    public void save(Dict dict)
    {
        dict.save();
    }


    public void update(Dict dict)
    {
        dict.update();
    }

    public void deleteById(int id)
    {
        Db.update("DELETE FROM bw_dict WHERE id="+id+" OR pid="+id);
    }
}
